/**
 * Created by netsnower on 16/4/12.
 */

var canvas, stage, exportRoot;
var count = 0;//loading百分比
var tipsTxt;//提示文本
var manifest, images;//图片加载列表
var isWap;
var loadingMc, loadingText;
var main, faq;

//touch变量
var iniY=0;//初始y位置
var tempY=0;//临时y位置
var iniTime=0;//初始时间
var nowTime=0;//当前时间

var audio_bg,audio_btn;
var reayAudio = false;
var firstPlay = true;
var isChecked = false;//是否检查了用户信息

var currentFaq=1;
var faqArr=[1,3,4,4,3,[1,2,3,4]];//正确答案
var selectAnswer=0;//选择的答案
var score=0;//成绩

//授权相关变量
var openid, openid_md5, nickname, sex, province, city, country, headimgurl;
var appname = 'LolGuessGame';//当前项目唯一标识，用来区分不同项目的cookie

//存储用户信息
var returnMyCustomer;
var customer_apply_score;//提交的成绩
var customer_apply_info=[];//提交的答案
var closer_percent;//后台返回比你成绩好的人百分比
var testNow=false;

function init() {
    iniUiScale();
    //delInfo();

    if (testNow) {
        homeState = 'begin';
        openid = 'ddd';
        openid_md5 = '7e1fd4bdb71af39f722134e8b93fc799';
        nickname = '小明';
        sex = '1';
        province = '北京';
        city = '北京';
        country = 'CN';
        headimgurl = 'http://wx.qlogo.cn/mmopen/BA8GZZ2EGwVckE3zlfIdkibgctJ22eS2fWYoB4rzNvV4rpFSLPQtRkOdhGcKPLDdkOEqbcxk2WOq5ofmVHqEaIw/0';
        initCjs();//测试使用
    } else {
        iniLogin();
    }
}
//授权，根据来路显示相应的界面
function iniLogin() {
    //alert(document.location.href);
    readInfo();
    if (openid != null) {
        //已经获得授权
        initCustomer();
    } else {
        //未授权
        //自动跳转到授权页面
        document.location.href = 'getopenid.php?gotourl=index.html&state=' + appname;
    }
}
//读取本地存储的用户信息，跳转到对应的画面
function readInfo() {
    openid = getCookie(appname + "_openid");
    openid_md5 = getCookie(appname + "_openid_md5");
    nickname = decodeURI(getCookie(appname + "_nickname"));
    sex = decodeURI(getCookie(appname + "_sex"));
    province = decodeURI(getCookie(appname + "_province"));
    city = decodeURI(getCookie(appname + "_city"));
    country = decodeURI(getCookie(appname + "_country"));
    headimgurl = decodeURIComponent(decodeURI(getCookie(appname + "_headimgurl")));
    if (String(headimgurl).indexOf('http') >= 0) {
        //shareImg=headimgurl;
    }
    //alert('openid='+openid+'\nopenid_md5='+openid_md5+'\nnickname='+nickname+'\nsex='+sex+'\nprovince='+province+'\ncity='+city+'\ncountry='+country+'\nheadimgurl='+headimgurl);
}
//删除cookie
function delInfo() {
    delCookie(appname + "_openid");
    delCookie(appname + "_openid_md5");
    delCookie(appname + "_nickname");
    delCookie(appname + "_sex");
    delCookie(appname + "_province");
    delCookie(appname + "_city");
    delCookie(appname + "_country");
    delCookie(appname + "_headimgurl");
    alert('cookies清除成功');
}
function iniBgSound() {
    var btnsound = new lib.BtnSound();
    btnsound.x = 570;
    btnsound.y = 10;
    btnsound.name='btn_audio_bg';
    stage.addChild(btnsound);
    btnsound.addEventListener('click', soundClickHandle);

    audio_bg = getEl('music_audio_bg');
    audio_bg.play();
    if (window.WeixinJSBridge) {
        WeixinJSBridge.invoke('getNetworkType', {}, function (e) {
            //alert('自动播放');
            if (firstPlay && audio_bg.currentTime == 0) {
                audio_bg.play();
                //home.btn_sound.visible=true;
                firstPlay = false;
            }
        });
    } else {
        document.addEventListener("WeixinJSBridgeReady", function () {
            WeixinJSBridge.invoke('getNetworkType', {}, function (e) {
                //alert('自动播放');
                if (firstPlay && audio_bg.currentTime == 0) {
                    audio_bg.play();
                    //home.btn_sound.visible=true;
                    firstPlay = false;
                }
            });
        }, false);

    }

    //背景音乐开关
    function soundClickHandle(evt) {
        if (checkPointID(evt)) {
            if (evt.currentTarget.currentFrame == 0) {
                evt.currentTarget.gotoAndStop(1);
                audio_bg.pause();
            } else {
                evt.currentTarget.gotoAndStop(0);
                audio_bg.play();
            }
        }
    }
}
//框架代码--------
function initCjs() {
    //audio_bg=getEl('music_audio_bg');
    //stageH = (640 / document.documentElement.clientWidth) * document.documentElement.clientHeight;
    canvas = getEl('mainCanvas');
    stage = new createjs.Stage(canvas);
    exportRoot = new lib.LolGuessGame();
    stage.addChild(exportRoot);
    stage.update();
    stage.enableMouseOver();

    createjs.Ticker.setFPS(lib.properties.fps);
    createjs.Ticker.addEventListener('tick', stage);
    preloading();
    iniFps();
}
//预载loading界面
function preloading() {
    //alert('预载');
    manifest = [
        {src: "images/loading.png", id: "loading"}
    ];

    var loader = new createjs.LoadQueue(false);
    //loader.installPlugin(createjs.Sound);
    loader.addEventListener('fileload', preloadingHandleFileLoad);
    loader.addEventListener('complete', preloadingHandleComplete);
    loader.loadManifest(manifest);
}
function preloadingHandleFileLoad(evt) {
    if (evt.item.type == 'image') {
        images[evt.item.id] = evt.result;
    }
}
function preloadingHandleComplete() {
    loading();
}
//loading
function loading() {
    loadingMc = new lib.LoadingMc();
    loadingMc.x = 0;
    exportRoot.addChild(loadingMc);

    images = images || {};
    var loader = new createjs.LoadQueue(false);
    //loader.installPlugin(createjs.Sound);
    loader.addEventListener('fileload', handleFileLoad);
    loader.addEventListener('complete', handleComplete);
    //loader.loadFile({src:"images/ShuangDan_atlas_.json", type:"spritesheet", id:"ShuangDan_atlas_"}, true);
    loader.loadManifest(lib.properties.manifest);
}
function handleFileLoad(evt) {
    if (evt.item.type == 'image') {
        images[evt.item.id] = evt.result;
    }
    count++;
    loadingMc.msg.text = (Math.floor(count / lib.properties.manifest.length * 100));
}

function handleComplete(evt) {
    iniHome();
    backLoading();
    iniBgSound();
}
//静默加载
function backLoading(){
    var manifest = [
        {src:"images/rbg.jpg", id:"rbg"},
        {src:"images/r11.png", id:"r11"},
        {src:"images/r12.png", id:"r12"},
        {src:"images/r21.png", id:"r21"},
        {src:"images/r22.png", id:"r22"},
        {src:"images/r31.png", id:"r31"},
        {src:"images/r32.png", id:"r32"},
        {src:"images/r41.png", id:"r41"},
        {src:"images/r42.png", id:"r42"},
        {src:"images/r51.png", id:"r51"},
        {src:"images/r52.png", id:"r52"},
        {src:"images/r61.png", id:"r61"},
        {src:"images/r62.png", id:"r62"}
    ];

    var loader = new createjs.LoadQueue(false);
    //loader.installPlugin(createjs.Sound);
    loader.addEventListener('fileload', handleFileLoad);
    loader.addEventListener('complete', handleComplete);
    loader.loadManifest(manifest);
    function handleFileLoad(evt) {
        if (evt.item.type == 'image') { images[evt.item.id] = evt.result; }
    }
    function handleComplete() {
        console.log('加载完所有结果页');
        iniWx();
    }
}
//初始化首页-------
function iniHome() {
    checkDevice();
    iniEvent();
    //清除loading
    exportRoot.removeChild(loadingMc);
    loadingMc = null;
    iniHomeMc();
}
function iniEvent() {
    if (createjs.Touch.isSupported()) {
        createjs.Touch.enable(stage);
    }
}
//显示fps
function iniFps() {
    var fpsLabel = new createjs.Text("-- fps", "bold 18px Arial", "#ccc");
    stage.addChild(fpsLabel);
    fpsLabel.x = 10;
    fpsLabel.y = 20;
    fpsLabel.visible = true;
    fpsLabel.addEventListener('tick', fpsEnterFrameHandle);
    function fpsEnterFrameHandle(evt) {
        fpsLabel.text = Math.round(createjs.Ticker.getMeasuredFPS()) + " fps";
    }
}

//初始化游戏界面
function iniHomeMc() {
    if (main) {
        exportRoot.removeChild(main);
        main = null;
    }
    main = new lib.HomeMc();
    exportRoot.addChild(main);
    main.hit.addEventListener('click',playClickHandle);
    main.gotoAndPlay(1);
}
//初始化问题
function iniFaq(id){
    if(faq){
        exportRoot.removeChild(faq);
        faq=null;
    }
    faq=eval('new lib.Question'+id+'();');
    //console.log(faq);
    pic=faq.pic;
    exportRoot.addChild(faq);
    faq.gotoAndPlay(1);

    faq.btn_answer1.name='answer1';
    faq.btn_answer2.name='answer2';
    faq.btn_answer3.name='answer3';
    faq.btn_answer4.name='answer4';

    faq.btn_answer1.selected=false;
    faq.btn_answer2.selected=false;
    faq.btn_answer3.selected=false;
    faq.btn_answer4.selected=false;

    faq.btn_answer1.addEventListener('click',answerUpHandle);
    faq.btn_answer2.addEventListener('click',answerUpHandle);
    faq.btn_answer3.addEventListener('click',answerUpHandle);
    faq.btn_answer3.addEventListener('click',answerUpHandle);
    faq.btn_answer4.addEventListener('click',answerUpHandle);

    if(id==6){
        selectAnswer=[];
    }else{
        selectAnswer=0;
    }
}
function removeAnswerEvent(){
    faq.btn_answer1.removeEventListener('click',answerUpHandle);
    faq.btn_answer2.removeEventListener('click',answerUpHandle);
    faq.btn_answer3.removeEventListener('click',answerUpHandle);
    faq.btn_answer3.removeEventListener('click',answerUpHandle);
    faq.btn_answer4.removeEventListener('click',answerUpHandle);
}
//下一个问题
function nextFaq(){
    //console.log('答案='+selectAnswer);
    //判断第6题答案，计分数
    if(currentFaq==6){
        if (selectAnswer.sort().toString() == faqArr[currentFaq - 1].sort().toString()) {
            score += 1;
            console.log('答案正确='+selectAnswer);
        }else{
            console.log('答案错误='+selectAnswer);
        }
    }
    customer_apply_info.push(selectAnswer);//保存用户答案
    console.log('成绩='+score);
    //判断是否到最后一题
    currentFaq++;
    if (currentFaq <= 6) {
        iniFaq(currentFaq);
    } else {
        stage.removeEventListener("stagemousedown",stagemousedownHandle);
        showResult(score);
        customer_apply_score=Math.floor(score/6*100);//计算为提交100分制成绩
    }
}

//显示结果
function showResult(level){
    if(faq){
        exportRoot.removeChild(faq);
        faq=null;
    }
    main=new lib.ResultMc();
    main.result1.visible=false;
    main.result2.visible=false;
    main.result3.visible=false;
    main.result4.visible=false;
    main.result5.visible=false;
    main.result6.visible=false;

    exportRoot.addChild(main);
    main.gotoAndPlay(1);
    if(level==0){
        level=1;
    }
    var result=eval('main.result'+level);
    result.visible=true;
    result.gotoAndPlay(1);
    setTimeout('showInfoForm()',500);
}
//显示中奖信息提交界面
function showInfoForm() {
    getEl('infoForm').style.display = 'block';
}
//显示提示文本
function alertMsg(msg){
    getEl('msg').innerHTML=msg;
    addClass(getEl('tips'), 'show');
}
function closeMsg(){
    removeClass(getEl('tips'), 'show');
}
//公用按钮按下事件
function btnMousedownHandle(evt) {
    if (checkPointID(evt)) {
        if(faq){
            //console.log(evt.currentTarget.selected);
            if(evt.currentTarget.selected){
                eval('faq.option'+evt.currentTarget.name.substr(6)+'.gotoAndStop(0);');
                evt.currentTarget.selected=false;
            }else{
                eval('faq.option'+evt.currentTarget.name.substr(6)+'.gotoAndPlay(1);');
                evt.currentTarget.selected=true;
            }
        }
    }
}
//开始按钮
function playClickHandle(evt){
    if (checkPointID(evt)) {
        exportRoot.removeChild(main);
        main=null;
        iniFaq(1);
        //delInfo();测试
    }
}
function answerUpHandle(evt){
    if(checkPointID(evt)){
        //stopSound();
        if(currentFaq==6){
            //如果是最后一题
            if(!evt.currentTarget.selected){
                evt.currentTarget.selected=true;
                selectAnswer.push(parseInt(evt.currentTarget.name.substr(6)));
                eval('faq.option'+parseInt(evt.currentTarget.name.substr(6))+'.ok.visible=true;');
            }else{
                evt.currentTarget.selected=false;
                selectAnswer.pop();
                eval('faq.option'+parseInt(evt.currentTarget.name.substr(6))+'.ok.visible=false;');
            }
        }else{
            removeAnswerEvent();
            //console.log(selectAnswer,parseInt(evt.currentTarget.name.substr(6)));
            selectAnswer=parseInt(evt.currentTarget.name.substr(6));
            if (selectAnswer == faqArr[currentFaq - 1]) {
                score += 1;
                console.log('答案正确='+selectAnswer);
                eval('faq.option'+selectAnswer+'.ok.visible=true;');
            }else{
                console.log('答案错误='+selectAnswer);
                eval('faq.option'+selectAnswer+'.err.visible=true;');
                eval('faq.option'+faqArr[currentFaq - 1]+'.ok.visible=true;');
            }
        }
        //选择答案后开启滑动切换
        stage.addEventListener("stagemousedown",stagemousedownHandle);
        faq.arrow.visible=true;
    }
}

//----------------上下滑动事件-------
function stagemousedownHandle(event){
    event.preventDefault();

    iniY=event.stageY;
    tempY=event.stageY;
    iniTime=new Date().getTime();

    stage.addEventListener("stagemousemove",stagemousemoveHandle);
    stage.addEventListener("stagemouseup",stagemouseupHandle);
}


function stagemousemoveHandle(event){
    event.preventDefault();
    //console.log(main.currentFrame);
}

function stagemouseupHandle(event){
    event.preventDefault();

    nowTime=new Date().getTime();
    if(event.stageY>iniY && (event.stageY>iniY+200 || (nowTime-iniTime)<500)){
        //判断用户是否向下移动了足够远

    }
    if(event.stageY<iniY && (event.stageY<iniY-200 || ((nowTime-iniTime)>100 && (nowTime-iniTime)<500))){
        //判断用户是否向上移动了足够远

        if(selectAnswer==0 || selectAnswer==[]){
            alertMsg('请选择答案!');
        }else{
            nextFaq();//下一关
            stage.removeEventListener("stagemousedown",stagemousedownHandle);
        }

    }

    iniY=event.stageY;
    tempY=event.stageY;
    iniTime=new Date().getTime();

    stage.removeEventListener("stagemousemove",stagemousemoveHandle);
    stage.removeEventListener("stagemouseup",stagemouseupHandle);
}
//控制ui自适应
function iniUiScale() {
    var p = document.documentElement.clientWidth / 640;
    getEl('infoForm').style.zoom = p;
    getEl('share').style.zoom = p;
    getEl('tips').style.zoom = p;
    getEl('end').style.zoom = p;
}


//提交数据--------------------------------
//存储用户信息
function initCustomer() {
    var params = [];
    params.push('openid=' + openid);
    params.push('openid_md5=' + openid_md5);
    params.push('nickname=' + nickname);
    params.push('sex=' + sex);
    params.push('province=' + province);
    params.push('city=' + city);
    params.push('country=' + country);
    params.push('headimgurl=' + headimgurl);
    console.log(params);
    sendRequest('http://hbweixin.twomi.cn/api_lol/initCustomer', function (res) {
        //alert(res.response);
        res = eval('(' + res.response + ')');
        if (res.success) {
            returnMyCustomer = res.addon.customer;
            initCjs();
        } else {
            //alert(res.detail);
            alertMsg(res.detail);
        }
    }, params.join('&'));
}

//提交个人信息
function submitForm(frm) {
    var params = [];
    params.push('customer_apply_score=' + customer_apply_score);
    params.push('customer_apply_info=' + customer_apply_info.join('-'));
    var email_reg = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;
    for (var i = 0, len = frm.elements.length; i < len; i++) {
        el = frm.elements[i];
        if (el.name == 'customer_name' && el.value == '') {
            alertMsg('请输入你的姓名!');
            return false;
        }
        if (el.name == 'customer_phone' && !(/^1(3|5|8)\d{9}$/.test(el.value))) {
            alertMsg('请输入正确的手机号码!');
            return false;
        }
        if (el.name && el.value !== '' && (el.type != 'radio' || el.checked)) {
            params.push(el.name + '=' + el.value);
        }
    }
    console.log(params);
    sendRequest(frm.action, function (res) {
        res = eval('(' + res.response + ')');
        //alert(res);
        if (res.success) {
            getEl('infoForm').style.display = 'none';
            getEl('end').style.display='block';
            closer_percent=res.addon.percent;
            changeShareTxt('我是lol中的老司机，超过'+closer_percent+'%的召唤师!');
        } else {
            alertMsg(res.detail);
        }
    }, params.join('&'));
}

//分享成功
function shareAction(){
    getEl('share').style.display='none';
}
//----------终端检测------
function checkDevice() {
    if (!navigator.userAgent.match(/mobile/i)) {
        //alert("当前设备为pc");
        isWap = false;
    } else {
        //alert("当前设备为移动");
        isWap = true;
    }
}
function checkPointID(evt) {
    if (isWap) {
        if (evt.pointerID != -1) {
            return true;
        } else {
            return false;
        }
    } else {
        if (evt.pointerID == -1) {
            return true;
        } else {
            return false;
        }
    }
}
//获取dom
function getEl(id) {
    return document.getElementById(id);
}
function checkPlatform() {
    if (/android/i.test(navigator.userAgent) && /MicroMessenger/i.test(navigator.userAgent)) {
        return 'android-wx';
    }
    if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent) && /MicroMessenger/i.test(navigator.userAgent)) {
        return 'ios-wx';
    }
    return false;
}
//更新分享信息
function changeShareTxt(txt){
    shareTitle=txt;
    //shareDesc='';
    iniWx();
}


//--------------分享-------------
var shareLink = 'http://hbweixin.twomi.cn/2016/2016_LolGuessGame/index.html';
var shareImg = 'http://hbweixin.twomi.cn/2016/2016_LolGuessGame/images/wxShare.jpg';
var shareTitle = '测测你是不是lol中的老司机';
var shareDesc = '';
function iniWx() {
    wx.config({
        debug: false,
        appId: signPackage.appId,
        timestamp: parseInt(signPackage.timestamp),
        nonceStr: signPackage.nonceStr,
        signature: signPackage.signature,
        jsApiList: [
            'checkJsApi',
            'onMenuShareTimeline',
            'onMenuShareAppMessage',
            'onMenuShareQQ',
            'onMenuShareWeibo'
        ]
    });
    //config接口处理成功后
    wx.ready(function () {
        // 1 判断当前版本是否支持指定 JS 接口，支持批量判断
        wx.checkJsApi({
            jsApiList: [
                'getNetworkType',
                'onMenuShareTimeline',
                'onMenuShareAppMessage',
                'onMenuShareQQ',
                'onMenuShareWeibo'
            ],
            success: function (res) {
                //alert(JSON.stringify(res));
                //网络+分享
                checkResult = eval('(' + JSON.stringify(res) + ')');
                checkResult = checkResult.checkResult;
                if (checkResult.getNetworkType) {
                    getNetworkType();
                }
                if (checkResult.onMenuShareTimeline) {
                    onMenuShareTimeline();
                }
                if (checkResult.onMenuShareAppMessage) {
                    onMenuShareAppMessage();
                }
                if (checkResult.onMenuShareQQ) {
                    onMenuShareQQ();
                }
                if (checkResult.onMenuShareWeibo) {
                    onMenuShareWeibo();
                }
            }
        });
    });
    //错误
    wx.error(function (res) {
        alert(res.errMsg);
    });
}
//------------------------------以下为常规接口-------------------------
//配置检测网络接口
function getNetworkType() {
    wx.getNetworkType({
        success: function (res) {
            console.log(res.networkType);
        },
        fail: function (res) {
            console.log(JSON.stringify(res));
        }
    });
}
//注册获取“发送给朋友”状态事件
function onMenuShareAppMessage() {
    wx.onMenuShareAppMessage({
        title: shareTitle,
        desc: shareDesc,
        link: shareLink,
        imgUrl: shareImg,
        trigger: function (res) {
            //alert('用户点击发送给朋友');
        },
        success: function (res) {
            //alert('已分享');
            shareAction();
        },
        cancel: function (res) {
            //alert('已取消');
        },
        fail: function (res) {
            //alert(JSON.stringify(res));
        }
    });
}
//注册获取“分享到朋友圈”状态事件
function onMenuShareTimeline() {
    wx.onMenuShareTimeline({
        title: shareTitle,
        link: shareLink,
        imgUrl: shareImg,
        trigger: function (res) {
            //alert('用户点击分享到朋友圈');
        },
        success: function (res) {
            //alert('已分享');
            shareAction();
        },
        cancel: function (res) {
            //alert('已取消');
        },
        fail: function (res) {
            //alert(JSON.stringify(res));
        }
    });
}
//注册获取“分享到 QQ”状态事件
function onMenuShareQQ() {
    wx.onMenuShareQQ({
        title: shareTitle,
        desc: shareDesc,
        link: shareLink,
        imgUrl: shareImg,
        trigger: function (res) {
            //alert('用户点击分享到QQ');
        },
        complete: function (res) {
            //alert(JSON.stringify(res));
        },
        success: function (res) {
            //alert('已分享');
        },
        cancel: function (res) {
            //alert('已取消');
        },
        fail: function (res) {
            alert(JSON.stringify(res));
        }
    });
}
//注册获取“分享到微博”状态事件
function onMenuShareWeibo() {
    wx.onMenuShareWeibo({
        title: shareTitle,
        desc: shareDesc,
        link: shareLink,
        imgUrl: shareImg,
        trigger: function (res) {
            //alert('用户点击分享到微博');
        },
        complete: function (res) {
            //alert(JSON.stringify(res));
        },
        success: function (res) {
            //alert('已分享');
        },
        cancel: function (res) {
            //alert('已取消');
        },
        fail: function (res) {
            //alert(JSON.stringify(res));
        }
    });
}